#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
import socketserver
from socket import *
import select

server = socket(AF_INET, SOCK_STREAM)
server.bind(("127.0.0.1", 28312))
server.listen(10)

read_list = [server]
write_list = []
x_list = []
data_dic = {}

while True:
    # select给操作系统发送一个请求, 操作系统去遍历所有连接
    # 如果有select就会拿到, 然后运行下一行代码, 如果没有就会原地阻塞
    rl, wl, xl = select.select(read_list, write_list, x_list)
    print("wl: {}, write_list: {}".format(wl, write_list))
    del_conn = []
    for sock in rl:
        if sock == server:
            conn, addr = sock.accept()
            read_list.append(conn)
        else:
            try:
                data = sock.recv(1024)      # 有消息的列表,读消息
                write_list.append(sock)     # 1、收到数据后 把消息放到要读的空列表里面
                # 因为如果文件过大就会让用户感觉到明显的等待,因为内存空间只有那么大,超过内存空间的大小就会一点点的读
                data_dic[sock] = data       # 2、用k:vlua的形式把消息存起来
            except ConnectionResetError:
                del_conn.append(sock)

    for sk in wl:       # 2、将收到的数据循环出来
        sk.send("hello world".encode("utf-8"))  # 循环消息列表,通过k拿到消息返回给客户端
        data_dic.pop(sk)              # 删除字典里的k
        write_list.remove(sk)         # 删除列表里的消息.因为这个消息已经读过了

    for conn_del in del_conn:
        read_list.remove(conn_del)
    print("read_list: {}".format(read_list))
